package net.thxjj.adminServer.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.thxjj.adminServer.service.IUserApiService;
import net.thxjj.sitermodel.User;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 登录拦截
 * @author rstyro
 *
 */
@WebFilter(filterName="loginFilter",urlPatterns={"/*"})
public class LoginFilter implements Filter{
	Logger logger = LoggerFactory.getLogger(getClass());
	
	//静态资源文件地址
	private static final String PTAH_REG=".*\\.((js)|(css)|(png)|(jpg)|(woff)|(woff2)|(map)|(svg)|(ttf)|(ico)|(json))";
	//不过滤的地址
	private static final String NOT_FILTER="/(upload/show)|(upload/exportTemplate).*";


	private static final String LOGIN_API="/((api/login)|(api/update)|(api/mongodb)|(upload/exportTemplate)).*";

	@Autowired
	private IUserApiService iUserApiService;

    @Override
    public void destroy() {}
    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
            throws IOException, ServletException {
    	 HttpServletRequest request = (HttpServletRequest) req;
         HttpServletResponse response = (HttpServletResponse) res;
         String path = request.getServletPath();
         if(!path.matches(PTAH_REG) && !path.matches(NOT_FILTER)){
				 if(SelfChekToken(request))
				 chain.doFilter(request, response);
				 else{
					if(path.matches(LOGIN_API)){
						chain.doFilter(request, response);
					}else{
						response.sendError(401);
					}
				 }
				 return;
         }
    	
        chain.doFilter(request, response);
    }
    @Override
    public void init(FilterConfig arg0) throws ServletException {
    }

	private boolean SelfChekToken(HttpServletRequest request){
		String token = request.getHeader("token");
		if(StringUtils.isEmpty(token)) {
			return false;
		}
		else{
			Long count = iUserApiService.getUserByToken(token);
			if(count <= 0){
				return false;
			}else{
				 User userinfo = iUserApiService.getUserInfoByToken(token);
				if((userinfo.getToken_time()+86400000)<System.currentTimeMillis()){
					return false;
				}else{
					return true;
				}

			}
		}

	}

}
